package org.wingstudio.controller.admin;


import net.sf.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.wingstudio.entity.News;
import org.wingstudio.entity.NewsType;
import org.wingstudio.entity.PageBean;
import org.wingstudio.entity.Picture;
import org.wingstudio.lucene.NewsIndex;
import org.wingstudio.service.NewsService;
import org.wingstudio.service.NewsTypeService;
import org.wingstudio.service.PictureService;
import org.wingstudio.util.PageUtil;
import org.wingstudio.util.ResponseUtil;
import org.wingstudio.util.StringUtil;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 新闻管理模块(工作动态,服务指南,招标信息)
 * Created by liao on 16-11-10.
 */
@Controller
@RequestMapping("/user/admin")
public class NewsController {

    @Resource
    private NewsService newsService;
    @Resource
    private NewsTypeService newsTypeService;
    @Resource
    private PictureService pictureService;

    private NewsIndex newsIndex=new NewsIndex();


    @RequestMapping("/addNews")
    public ModelAndView addNews()throws Exception{
        ModelAndView modelAndView=new ModelAndView();

        List<NewsType> newsTypes=newsTypeService.countList();
        modelAndView.addObject("newsTypes",newsTypes);
        modelAndView.setViewName("user/admin/build/new");
        return modelAndView;
    }

    /**
     * 保存新闻
     * @param news
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/update")
    public String update(News news, HttpServletResponse response)
            throws Exception {
        String content=news.getContent();
        Integer i=newsService.update(news);
        //newsIndex.updateIndex(news);
        JSONObject result=new JSONObject();
        result.put("success", true);
        ResponseUtil.write(response, result);
        return null;
    }

    @RequestMapping("/saveNews")
    public String saveNews(News news, HttpServletResponse response,
                           HttpServletRequest request)
            throws Exception {
        ServletContext application= RequestContextUtils.getWebApplicationContext
                (request).getServletContext();
        if (news.getNewsTypeId()==1||news.getNewsTypeId()==2||news.getNewsTypeId()==3){
            String content=news.getContent();

            Document doc= Jsoup.parse(content);
            Elements elements=doc.select("img");
            for (int i = 0; i < elements.size(); i++){
                Element element=elements.get(i);
                Picture picture=pictureService.find();
                Picture p=new Picture();
                p.setImgUrl(element.attr("src"));
                BufferedImage bufferedImage= ImageIO.read(new File("/opt/apache-tomcat-9.0.0.M10/webapps"+p.getImgUrl()));
                if(bufferedImage.getWidth()>680){
                    String testContent1=news.getContent();
                    String testContent=testContent1.replace("src=\""+p.getImgUrl()+"\"","src=\""+p.getImgUrl()+"\""+" style=\"width:87%\""+"");
                    news.setContent(testContent);
                }
                p.setFlag(picture.getFlag()+1);
                pictureService.add(p);
                pictureService.remove();
            }
            List<Picture> pictureList=pictureService.list();
            Picture p1=pictureList.get(0);
            Picture p2=pictureList.get(1);
            Picture p3=pictureList.get(2);
            Picture p4=pictureList.get(3);
            Picture p5=pictureList.get(4);


            application.setAttribute("p1",p1);
            application.setAttribute("p2",p2);
            application.setAttribute("p3",p3);
            application.setAttribute("p4",p4);
            application.setAttribute("p5",p5);

            Integer i=newsService.add(news);
            News testNew=newsService.getLast();
            List<News> recentNews=newsService.getRecent();
            application.setAttribute("recentNews",recentNews);
            newsIndex.addIndex(testNew);
            JSONObject result=new JSONObject();
            result.put("success", true);
            ResponseUtil.write(response, result);

        }else {
            JSONObject result=new JSONObject();
            result.put("success", false);
            ResponseUtil.write(response, result);
        }
        return null;
    }

    /**
     * 列出后台所有的新闻
     * @param page
     * @return
     * @throws Exception
     */
    @RequestMapping("/work")
    public ModelAndView listWorks(@RequestParam(value="page",required=false)String page,
                                 HttpServletRequest request)
    throws Exception{
        ModelAndView modelAndView=new ModelAndView();
        if(StringUtil.isEmpty(page)){
            page="1";
        }
        PageBean pageBean=new PageBean(Integer.parseInt(page),10);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("start", pageBean.getStart());
        map.put("size", pageBean.getPageSize());
        map.put("newsTypeId",1);
        List<News> newsList=newsService.list(map);

        Long sum=newsService.getTotal(map);
        modelAndView.addObject("sum",sum);
        modelAndView.addObject("pageCode", PageUtil.genPagination(request.getContextPath()+"/user/admin/work",
                newsService.getTotal(map), Integer.parseInt(page), 10));
        modelAndView.addObject("workList",newsList);
        modelAndView.setViewName("user/admin/news/workManage");
        return modelAndView;
    }

    @RequestMapping("/service")
    public ModelAndView listServices(@RequestParam(value="page",required=false)String page,
                                 HttpServletRequest request)
            throws Exception{
        ModelAndView modelAndView=new ModelAndView();
        if(StringUtil.isEmpty(page)){
            page="1";
        }
        PageBean pageBean=new PageBean(Integer.parseInt(page),10);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("start", pageBean.getStart());
        map.put("size", pageBean.getPageSize());
        map.put("newsTypeId",2);
        List<News> newsList=newsService.list(map);
        Long sum=newsService.getTotal(map);
        modelAndView.addObject("sum",sum);

        modelAndView.addObject("pageCode", PageUtil.genPagination(request.getContextPath()+"/user/admin/service",
                newsService.getTotal(map), Integer.parseInt(page), 10));
        modelAndView.addObject("serviceList",newsList);
        modelAndView.setViewName("user/admin/news/serviceManage");
        return modelAndView;
    }

    @RequestMapping("/tender")
    public ModelAndView listTenders(@RequestParam(value="page",required=false)String page,
                                     HttpServletRequest request)
            throws Exception{
        ModelAndView modelAndView=new ModelAndView();
        if(StringUtil.isEmpty(page)){
            page="1";
        }
        PageBean pageBean=new PageBean(Integer.parseInt(page),10);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("start", pageBean.getStart());
        map.put("size", pageBean.getPageSize());
        map.put("newsTypeId",3);
        List<News> newsList=newsService.list(map);

        Long sum=newsService.getTotal(map);
        modelAndView.addObject("sum",sum);
        modelAndView.addObject("pageCode", PageUtil.genPagination(request.getContextPath()+"/user/admin/tender",
                newsService.getTotal(map), Integer.parseInt(page), 10));
        modelAndView.addObject("tenderList",newsList);
        modelAndView.setViewName("user/admin/news/tenderManage");
        return modelAndView;
    }

    /**
     * 通过id查找实体
     * @param id
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/findById")
    public String findById(@RequestParam(value="id")String id,HttpServletResponse response)
            throws Exception{
        News news=newsService.findById(Integer.parseInt(id));

        JSONObject jsonObject=JSONObject.fromObject(news);
        ResponseUtil.write(response, jsonObject);
        return null;
    }

    @RequestMapping("/delete")
    public String delete(@RequestParam(value="element")String id,HttpServletResponse response)
            throws Exception{
        newsService.delete(Integer.parseInt(id));
        //blogIndex.deleteIndex(idsStr[i]); // 删除对应的索引
        JSONObject result=new JSONObject();
        result.put("success", true);
        ResponseUtil.write(response, result);
        return null;
    }

    @RequestMapping("/updateNews/{id}")
    public ModelAndView updateNews(@PathVariable("id") Integer id)throws Exception{
        ModelAndView modelAndView=new ModelAndView();
        News news=newsService.findById(id);
        List<NewsType> newsTypes=newsTypeService.countList();
        modelAndView.addObject("newsTypes",newsTypes);
        modelAndView.addObject("news",news);
        modelAndView.setViewName("user/admin/update/new");
        return modelAndView;
    }

    @RequestMapping("/toTop")
    public String toTopNews(@RequestParam(value="id")String id,
                            HttpServletResponse response)throws Exception{

        News topNews=newsService.selectTop();
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("top",topNews.getToTop()+1);
        map.put("id",Integer.parseInt(id));
        newsService.toTopNews(map);
        JSONObject result=new JSONObject();
        result.put("success", true);
        ResponseUtil.write(response, result);
        return null;
    }

    @RequestMapping("cancelTop")
    public String cancelTop(@RequestParam(value="id")String id,
                            HttpServletResponse response)throws Exception{
        newsService.cancelTop(Integer.parseInt(id));
        JSONObject result=new JSONObject();
        result.put("success", true);
        ResponseUtil.write(response, result);
        return null;
    }

    @RequestMapping("/search")
    public ModelAndView search(HttpServletRequest request)throws Exception{
        ModelAndView modelAndView=new ModelAndView();
        String content=request.getParameter("content");
        List<News> newsList=newsIndex.searchNews(content);

        modelAndView.addObject("newsList",newsList);
        modelAndView.setViewName("user/admin/news/searchResult");
        return modelAndView;
    }

}